<template>
  <div class="flex border-t query">
    <div class="w-2/12 bg-gray-50 p-1">
      <div class="flex justify-between p-2">
        查询条件
        <a-button size="mini" @click="add" type="text"> 添加 </a-button>
      </div>
      <draggable v-model="query" class="layer-list" item-key="zIndex" :animation="200">
        <template #item="{ element, index }">
          <a-list
            size="small"
            :class="queryForm.label === element.label ? 'active' : ''"
            @click="clickQuery(element, index)"
          >
            <a-list-item class="cursor-pointer !p-3">
              <div class="flex items-center justify-between">
                {{ element.label }}
                <div>
                  <a-button type="text" size="small" @click.stop="element.hidden = !element.hidden">
                    <template #icon>
                      <span :class="element.hidden ? 'bi-eye-line' : 'bi-eye-fill'" />
                    </template>
                  </a-button>
                  <a-button type="text" size="small" class="bi-x-lg" @click.stop="queryDel(index)">
                    <template #icon>
                      <span class="bi-close-line" />
                    </template>
                  </a-button>
                </div>
              </div>
            </a-list-item>
          </a-list>
        </template>
      </draggable>
    </div>
    <div class="w-10/12 p-1" v-if="queryForm.component && Object.keys(queryForm.component).length > 0">
      <a-form v-model="queryForm" layout="inline" label-width="70px">
        <a-form-item label="标签" name="label">
          <a-input size="small" v-model="queryForm.label" />
        </a-form-item>
      </a-form>
      <div class="flex mt-2 p-1 border-t" v-if="queryForm.component && Object.keys(queryForm.component).length > 0">
        <div class="w-4/12 border-r">
          <div class="pl-2 title-desc">关联组件和字段</div>
          <vxe-table
            border="none"
            ref="tableRef"
            height="500"
            :row-config="{ keyField: 'key' }"
            :data="queryComponentList"
            @checkbox-all="selectAllChangeEvent"
            @checkbox-change="selectChangeEvent"
          >
            <vxe-column type="checkbox" width="60" />
            <vxe-column field="title" title="组件名称">
              <template #default="{ row }">
                <div>{{ row.element.title || row.title }}</div>
              </template>
            </vxe-column>
            <vxe-column field="age" title="字段">
              <template #header> 字段 </template>
              <template #default="{ row }">
                <vxe-select
                  size="small"
                  v-model="queryForm.component[row.key].field"
                  @change="setFields(queryForm.component[row.key])"
                  clearable
                  filterable
                  transfer
                >
                  <vxe-option
                    v-for="item in row.data.fields"
                    :key="item.fieldId"
                    :value="item.fieldId"
                    :label="item.field + item.title"
                  >
                    <template #default="{ option }">
                      <span class="text-sm">{{ option.label }}</span>
                    </template>
                  </vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
        <div class="w-7/12 pl-2">
          <Filter v-if="queryForm" v-model:filter="queryForm.filter" v-model:currentComponent="currentComponent" />
        </div>
      </div>
    </div>
    <div v-else>请添加组件</div>
  </div>
</template>

<script setup>
import draggable from "vuedraggable"
import { useVModel } from "@vueuse/core"
import { useComponent } from "@/hooks/userEditor"
import Filter from "./filter.vue"
const props = defineProps({
  modelValue: {
    type: Array
  }
})
const emit = defineEmits(["update:modelValue"])
const query = useVModel(props, "modelValue", emit)
const { componentList } = useComponent()

const queryComponentList = computed(() => {
  return componentList.value.filter((item) => item.data.cube_id)
})
const defaultFilterOption = {
  type: "input",
  filterType: "1",
  // 过滤形式
  filterForm: "1",
  isDefault: false,
  // 过滤条件
  filterCondition: {
    function: ["like", "<="],
    value: ["", ""],
    default: ["", ""],
    // 排除选择的数据
    exclude: false
  },
  // 枚举对象
  enum: {
    content: [],
    code: ""
  },
  // 日期参数
  date: {
    type: "day",
    startDate: {
      // 日期类型
      dateType: "day",
      // 相对时间 + -
      dateRelative: "-",
      // 日期值
      dateValue: 1,
      // 日期天数
      dateDay: ""
    },
    endDate: {
      // 日期类型
      dateType: "day",
      // 相对时间 + -
      dateRelative: "-",
      // 日期值
      dateValue: 1,
      // 日期天数
      dateDay: ""
    }
  }
}
const add = () => {
  query.value.push({
    label: "未命名" + (query.value.length + 1),
    placeholder: "",
    // 是否隐藏
    hidden: false,
    // 组件列表
    component: {},
    // 筛选条件
    filter: defaultFilterOption
  })
  clickQuery(query.value[query.value.length - 1], query.value.length - 1)
}

// 查询条件
const queryForm = ref({})
const queryIndex = ref({})
const tableRef = ref()
const currentComponent = ref()
// 点击查询条件
const clickQuery = async (item, index) => {
  await nextTick()
  queryComponentList.value.forEach((v) => {
    item.component[v.key] = {
      ...v,
      ...{
        checked: true
      },
      ...item.component[v.key]
    }
  })
  queryForm.value = item
  currentComponent.value = item.component[Object.keys(item.component)[0]]
  queryIndex.value = index
  setTimeout(() => {
    tableRef.value.clearCheckboxRow()
    const checkboxRecords = []
    Object.keys(item.component).forEach((key) => {
      if (item.component[key].checked) {
        checkboxRecords.push({
          key: key
        })
      }
    })
    tableRef.value.setCheckboxRow(checkboxRecords, true)
  }, 100)
}
// 删除查询条件
const queryDel = (index) => {
  query.value.splice(index, 1)
  queryForm.value = {}
  queryIndex.value = {}
}

const selectAllChangeEvent = ({ checked }) => {
  const $table = tableRef.value
  if ($table) {
    const records = $table.getCheckboxRecords()
    records.forEach((item) => {
      queryForm.value.component[item.key].checked = checked
    })
  }
}
const selectChangeEvent = ({ checked }) => {
  const $table = tableRef.value
  if ($table) {
    const records = $table.getCheckboxRecords()
    Object.keys(queryForm.value.component).forEach((key) => {
      if (records.find((item) => item.key === key)) {
        queryForm.value.component[key].checked = true
      } else {
        queryForm.value.component[key].checked = false
      }
    })
  }
}

const setFields = (compoent) => {
  compoent.fieldQuery = compoent.data.fields.find((v) => v.fieldId === compoent.field)
}
onMounted(() => {
  if (query.value.length) {
    queryForm.value = clickQuery(query.value[0], 0)
  }
})
</script>

<style scoped lang="less">
.query {
  background: #fff;
  &-list {
    padding: 5px;
    border-bottom: 1px solid #ccc;
    &:hover {
      background: #f5f5f5;
    }
    // 选中
    &.active {
      background: #f5f5f5;
    }
    &:last-child {
      border-bottom: none;
    }
  }
}
</style>
